package com.webSocket;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

@ServerEndpoint("/websocket")
public class Wssocket {
    static Set<Session> set = new HashSet<Session>();
   static Iterator<Session> iter = set.iterator();


    //定义Session记录访问状态
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接建立成功！");
        String str = session.getQueryString();//获取前台传参
        try {
            str = URLDecoder.decode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        System.out.println("这是" + str);//str是每个用户的用户名
        set.add(session);
    }

    @OnClose
    public void onClose() {
     try {
         while (iter.hasNext()) {
             iter.remove();
         }
     }catch (Exception e){
         e.printStackTrace();
     }
        System.out.println("连接已关闭！");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        String str = session.getQueryString();//这里要确保以当前session为准给其它所有存入set的session发信息 不然会出错
        try {
            str = URLDecoder.decode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        message = message + str;
        System.out.println("信息接收！" + message);
        for (Session s : set) {
            try {
                s.getBasicRemote().sendText(message);     //也要把user的str发过去
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        System.out.println("系统异常");
    }

}
